package com.one.wishes;

import com.one.wishes.act.ActivityChangeAccount;
import com.one.wishes.dao.MyDataBase;
import com.one.wishes.ui.popmenu.DropPopMenu;
import com.one.wishes.ui.popmenu.MenuItem;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseExpandableListAdapter;
import android.widget.CursorTreeAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;

import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import java.util.ArrayList;
import java.util.List;

import static com.one.wishes.dao.MyDataBase.TABLE_NAME_LIMIT;

public class Fragment_History extends Fragment {

	private int[] group_checked = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
	private View view;
	private ExpandableListView e_list;
	private TextView tvEmpty;
	private MyDataBase dataBase;
	private MyCursrTreeAdapter myCursorTreeAdapter;
	private static final int groupName_index = 1;
	private static final int time_index = 3;
	private static final int type_index = 1;
	private static final int money_index = 2;
	private static final int mark_index = 6;
	private static final int id_index = 0;
	int groupNameIndex;
	String mygroupName;
	Cursor groupCursor;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (view == null) {
			view = inflater.inflate(R.layout.content_history, container, false);
			tvEmpty = (TextView) view.findViewById(R.id.history_list_empty);
			e_list = (ExpandableListView) view.findViewById(R.id.history_list);
			e_list.setGroupIndicator(null);
			e_list.setEmptyView(tvEmpty);
			dataBase = new MyDataBase(getContext());
			dataBase.open();
		}
		ViewGroup parent = (ViewGroup) view.getParent();
		if (parent != null) {
			parent.removeView(view);
		}
		initAdapterView();
		return view;
	}



	private void initAdapterView() {
		// TODO initAdapterView
		groupCursor = dataBase.getAccountByGroups(0, "");
		// getActivity().startManagingCursor(groupCursor);
		groupNameIndex = groupCursor.getColumnIndexOrThrow("_month");
		myCursorTreeAdapter = new MyCursrTreeAdapter(groupCursor, getContext(),
				true);
		e_list.setAdapter(myCursorTreeAdapter);
		e_list.setOnGroupClickListener(new OnGroupClickListener() {

			@Override
			public boolean onGroupClick(ExpandableListView parent, View v,
					int groupPosition, long id) {
				group_checked[groupPosition] = group_checked[groupPosition] + 1;
				((BaseExpandableListAdapter) myCursorTreeAdapter)
						.notifyDataSetChanged();
				return false;
			}
		});
		e_list.setOnChildClickListener(new OnChildClickListener() {

			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {

				onClickPopIcon(v,groupPosition,childPosition);

				((BaseExpandableListAdapter) myCursorTreeAdapter)
						.notifyDataSetChanged();
				return false;
			}
		});
	}

	public void onClickPopIcon(View view,int groupPosition, int childPosition) {
		DropPopMenu dropPopMenu = new DropPopMenu(getActivity());
		dropPopMenu.setTriangleIndicatorViewColor(Color.LTGRAY);
//        dropPopMenu.setBackgroundResource(R.drawable.bg_drop_pop_menu_white_shap);
		dropPopMenu.setBackgroundResource(R.drawable.bg_drop_pop_menu_shap);
		dropPopMenu.setItemTextColor(Color.BLACK);
		dropPopMenu.setIsShowIcon(true);

		dropPopMenu.setOnItemClickListener(new DropPopMenu.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapterView, View view, int position, long id, MenuItem menuItem) {
				if(menuItem.getItemId() == 1){
					//修改
					Cursor childCursor = myCursorTreeAdapter.getChild(groupPosition,childPosition);
					String time = childCursor.getString(time_index);
					String type = childCursor.getString(type_index);
					String money = childCursor.getString(money_index);
					String mark = childCursor.getString(mark_index);
					int idd = childCursor.getInt(id_index);
					Intent it = new Intent();
					it.putExtra("time",time);
					it.putExtra("type",type);
					it.putExtra("money",money);
					it.putExtra("mark",mark);
					it.putExtra("idd",idd);
					it.setClass(getActivity(), ActivityChangeAccount.class);
					startActivityForResult(it,11);

				}else if(menuItem.getItemId() == 2){
					//删除
					AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.AlertDialog);
					builder.setTitle("删除该记录");
					builder.setCancelable(false);
					//builder.setMessage(updateMsg);
					builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							Cursor childCursor = myCursorTreeAdapter.getChild(groupPosition,childPosition);
							String time = childCursor.getString(time_index);
							String type = childCursor.getString(type_index);
							String money = childCursor.getString(money_index);
							String mark = childCursor.getString(mark_index);
							int idd = childCursor.getInt(id_index);
							dataBase.deleteData("accounts", "_id", String.valueOf(idd));
							((BaseExpandableListAdapter) myCursorTreeAdapter)
									.notifyDataSetChanged();

							//更新图表
							String used = dataBase.getProORLimit(0, type);
							String limit = dataBase.getProORLimit(2, type);
							float f =   Float.parseFloat(used) - Float.parseFloat(money);
							dataBase.updateDataTolimitsUsed(type, f);
							if (!limit.equals("0")) {
								dataBase.updateDataTolimitsLimit(type, limit,
										String.valueOf(f));
//							}else{
//								dataBase.deleteData(TABLE_NAME_LIMIT,type, limit );
							}
						}
					});
					builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();

						}
					});
					AlertDialog noticeDialog = builder.create();
					noticeDialog.setCancelable(false);
					noticeDialog.setCanceledOnTouchOutside(false);
					noticeDialog.show();
				}
			}
		});
		dropPopMenu.setMenuList(getIconMenuList());
		dropPopMenu.show(view);
	}

	private List<MenuItem> getIconMenuList() {
		List<MenuItem> list = new ArrayList<>();
		list.add(new MenuItem(R.drawable.setsign, 1, "修改"));
		list.add(new MenuItem(R.drawable.clear_softcert, 2, "删除"));
		return list;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		groupCursor.close();
		dataBase.close();
	}



	public class MyCursrTreeAdapter extends CursorTreeAdapter {

		public MyCursrTreeAdapter(Cursor cursor, Context context,
								  boolean autoRequery) {
			super(cursor, context, autoRequery);
		}

		@Override
		protected void bindGroupView(View view, Context context, Cursor cursor,
									 boolean isExpanded) {
			// TODO bindGroupView
			TextView group_title = (TextView) view
					.findViewById(R.id.group_title);
			String group = cursor.getString(groupName_index);
			group_title.setText(group);
			TextView groupCount = (TextView) view
					.findViewById(R.id.group_count);
			int count = dataBase.getCount(3, "accounts", group);
			groupCount.setText("[" + count + "]");
			ImageView group_state = (ImageView) view
					.findViewById(R.id.group_state);
			if (isExpanded) {
				group_state.setBackgroundResource(R.drawable.group_up);
			} else {
				group_state.setBackgroundResource(R.drawable.group_down);
			}
		}

		@Override
		protected View newGroupView(Context context, Cursor cursor,
									boolean isExpanded, ViewGroup parent) {
			LayoutInflater inflate = LayoutInflater.from(getContext());
			View view = inflate.inflate(
					R.layout.content_history_e_list_parent_item, parent, false);

			bindGroupView(view, context, cursor, isExpanded);

			return view;
		}

		@Override
		protected Cursor getChildrenCursor(Cursor groupCursor) {
			String groupName = groupCursor.getString(groupName_index);
			Cursor childCursor = dataBase.getAccountByGroups(1, groupName);
			return childCursor;
		}

		@Override
		protected View newChildView(Context context, Cursor cursor,
									boolean isLastChild, ViewGroup parent) {
			LayoutInflater inflate = LayoutInflater.from(getContext());
			View view = inflate.inflate(
					R.layout.content_history_e_list_child_item, parent, false);
			bindChildView(view, context, cursor, isLastChild);
			return view;
		}

		@Override
		protected void bindChildView(View view, Context context, Cursor cursor,
									 boolean isLastChild) {
			// TODO bindChildView
			TextView time = (TextView) view.findViewById(R.id.child_text_time);
			time.setText(cursor.getString(time_index));
			TextView type = (TextView) view.findViewById(R.id.child_text_type);
			type.setTextKeepState(cursor.getString(type_index));
			TextView money = (TextView) view
					.findViewById(R.id.child_text_money);
			money.setTextKeepState(cursor.getString(money_index) + " "
					+ getString(R.string.rmb));
			TextView mark = (TextView) view.findViewById(R.id.child_text_mark);
			mark.setTextKeepState(cursor.getString(mark_index));
		}
	}


	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 11 && resultCode == 11) {
			//更新图表
			String type = data.getStringExtra("type");
			String oldMoney = data.getStringExtra("oldMoney");
			String money = data.getStringExtra("money");
			String used = dataBase.getProORLimit(0, type);
			String limit = dataBase.getProORLimit(2, type);
			float f =   Float.parseFloat(used) + Float.parseFloat(money) - Float.parseFloat(oldMoney);
			dataBase.updateDataTolimitsUsed(type, f);
			if (!limit.equals("0")) {
				dataBase.updateDataTolimitsLimit(type, limit,
						String.valueOf(f));
//							}else{
//								dataBase.deleteData(TABLE_NAME_LIMIT,type, limit );
			}
			((BaseExpandableListAdapter) myCursorTreeAdapter)
					.notifyDataSetChanged();
		}
	}

}
